<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="78px">
        <el-form-item label="使用部门">
          <SelectOriganizationDangerGrant
            @change="(ids:string) => getSelectIds(ids, '使用部门')"
            :isCheckStrictly="true"
            :isMultiple="false"
            :disabled="false"
            :data="dataObject('使用部门')"
            :selectData="searchParam.usingDepartmentId"
          />
        </el-form-item>

        <el-form-item label="企业编号">
          <el-input
            v-model="searchParam.assetCode"
            placeholder="请输入企业编号"
            clearable
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item label="器具状态">
          <el-select
            v-model="searchParam.assetStatus"
            placeholder="请选择器具状态"
            @keyup.enter="search"
            clearable
          >
            <el-option
              v-for="item in dictionaryStore.filterDictList('mtAssetStatus')"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="位置">
          <el-tree-select
            placeholder="请输入位置"
            filterable
            v-model="searchParam.locationId"
            :data="locationInfoTree"
            node-key="id"
            clearable
            :props="{ label: 'locationName', children: 'nodes' }"
            check-strictly
            :render-after-expand="false"
          />
        </el-form-item>
        <el-form-item label="产品">
          <el-select
            v-model="searchParam.productId"
            placeholder="产品"
            @keyup.enter="search"
            clearable
          >
            <el-option
              v-for="item in productList"
              :key="`${item.id}`"
              :label="`${item.productName}`"
              :value="`${item.id}`"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="器具类型" prop="assetTypeId">
          <el-tree-select
            placeholder="请选择器具类型"
            v-model="searchParam.assetTypeId"
            :data="catalogList"
            node-key="id"
            :props="{
              label: 'assetTypeName',
              value: 'id',
              children: 'nodes',
            }"
            :render-after-expand="false"
            :check-strictly="true"
            clearable
          />
        </el-form-item>

        <el-form-item label="待检定日期">
          <el-date-picker
            v-model="searchParam.nextCheckDateSearch"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            @change="getcreateTime"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="reset"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button
          @click="
            useDownload('/eam/mtAssetInfo/export', '检具清单', searchParam)
          "
        >
          <template #icon><i-ep-download /></template>导出</el-button
        >
      </template>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
        @sort-change="onTableSortChanged"
      >
        <!-- 表格内容操作 -->
        <template v-for="item in tableColumns" :key="item">
          <TableColumn v-if="item.prop && item.isShow" :column="item">
            <template v-for="slot in Object.keys($slots)" #[slot]="scope">
              <slot :name="slot" v-bind="scope"></slot>
            </template>
          </TableColumn>
        </template>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 列设置 抽屉组件 -->
    <ColSetting
      v-model:col-setting="tableColumns"
      v-model:search-setting="searchColumns"
      @search-handle="(e: boolean) => (showSearch = e)"
    />
  </div>
</template>

<script setup lang="tsx">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook();
import { filterOrder } from "@/utils/commonHooks";

import dayjs from "dayjs";
defineOptions({
  name: "EAMMTINSPECTIONTOOLLIST",
  inheritAttrs: false,
});

/** 自定义设置方法   start **/

// 搜索参数 设置为响应式
const searchColumns: any = reactive([
  // {
  //   type: "select", // 普通输入框
  //   isShow: true,
  //   label: "使用部门", // 标签文本
  //   fieldName: "usingDepartmentId", // 字段名称
  //   placeholder: "请输入看板编号", // 提示文字
  //   initValue: "", // 默认值
  // },
  // {
  //   type: "select", // 普通输入框
  //   isShow: true,
  //   label: "位置", // 标签文本
  //   fieldName: "locationId", // 字段名称
  //   placeholder: "请输入看板名称", // 提示文字
  //   initValue: "", // 默认值
  // },
  // {
  //   type: "select", // 普通输入框
  //   isShow: true,
  //   label: "产品", // 标签文本
  //   fieldName: "catalogId", // 字段名称
  //   placeholder: "请输入目录主键", // 提示文字
  //   initValue: "", // 默认值
  // },
  // {
  //   type: "select",
  //   label: "状态",
  //   isShow: true,
  //   fieldName: "assetStatus",
  //   placeholder: "请选择看板类型",
  //   initValue: null,
  //   defaultFirstOption: true,
  //   optionList: useDictionary("DataBoardType"),
  // },
  // {
  //   type: "select",
  //   label: "管理部门",
  //   isShow: true,
  //   fieldName: "databoradType",
  //   placeholder: "请选择看板类型",
  //   initValue: null,
  //   defaultFirstOption: true,
  //   optionList: useDictionary("DataBoardType"),
  // },
  // {
  //   type: "select",
  //   label: "器具",
  //   isShow: true,
  //   fieldName: "assetName",
  //   placeholder: "请选择看板类型",
  //   initValue: null,
  //   defaultFirstOption: true,
  //   optionList: useDictionary("DataBoardType"),
  // },
  // {
  //   type: "select",
  //   label: "日期",
  //   isShow: true,
  //   fieldName: "nextCheckDateSearch",
  //   placeholder: "请选择看板类型",
  //   initValue: null,
  //   defaultFirstOption: true,
  //   optionList: useDictionary("DataBoardType"),
  // },
]);

// 接收 columns 并设置为响应式
const tableColumns = reactive([
  {
    prop: "assetCode",
    label: "器具编号",
    isShow: true,
    minWidth: "120",
    align: "left",
    sortable: "sortable",
  },
  {
    prop: "assetName",
    label: "器具名称",
    isShow: true,
    minWidth: "120",
    align: "left",
    sortable: "sortable",
  },
  // {
  //   prop: "assetModelNo",
  //   label: "品牌型号",
  //   isShow: true,
  //   minWidth: "120",
  //   sortable: "sortable",
  //   render: (scope: any) => (
  //     <span>
  //       {scope.row.assetBrandName}
  //       {scope.row.assetModelNo && scope.row.assetBrandName ? "-" : ""}
  //       {scope.row.assetModelNo}
  //     </span>
  //   ),
  // },
  {
    prop: "measuringRange",
    label: "测量范围",
    isShow: true,
    minWidth: "120",
    sortable: "sortable",
  },
  // {
  //   prop: "measuringAccuracy",
  //   label: "精度",
  //   width: 120,
  //   isShow: true,
  //   sortable: "sortable",
  // },
  {
    prop: "measuringDivision",
    label: "分度",
    isShow: true,
    sortable: "sortable",
  },
  {
    prop: "makerName",
    label: "制造商",
    width: 120,
    sortable: "sortable",
    isShow: true,
    align: "left",
    // render: (scope: any) =>
    //   scope.row.enabled !== 1 ? (
    //     <el-tag type="info">
    //       {useDictionary("Enabled", scope.row.enabled)}
    //     </el-tag>
    //   ) : (
    //     <el-tag type="success">
    //       {useDictionary("Enabled", scope.row.enabled)}
    //     </el-tag>
    //   ),
  },
  {
    prop: "assetSpecification",
    label: "规格",
    isShow: true,
    minWidth: "120",
    sortable: "sortable",
    // render: (scope: any) => <span>{scope.row.remarks || "--"}</span>,
  },
  {
    prop: "manufactureCode",
    label: "出厂编号",
    isShow: true,
    minWidth: "120",
    sortable: "sortable",
    // render: (scope: any) => <span>{scope.row.remarks || "--"}</span>,
  },
  {
    prop: "usingDate",
    label: "使用日期",
    isShow: true,
    minWidth: "120",
    sortable: "sortable",
    render: (scope: any) =>
      scope.row.usingDate ? (
        <span>{dayjs(scope.row.usingDate).format("YYYY-MM-DD")}</span>
      ) : (
        <span>{""}</span>
      ),
  },

  {
    prop: "checkPeriod",
    label: "检定周期",
    isShow: true,
    sortable: "sortable",
    minWidth: "120",
  },
  {
    prop: "nextCheckDate",
    label: "检定到期日",
    isShow: true,
    sortable: "sortable",
    minWidth: "120",
    render: (scope: any) =>
      scope.row.nextCheckDate ? (
        <span>{dayjs(scope.row.nextCheckDate).format("YYYY-MM-DD")}</span>
      ) : (
        <span>{""}</span>
      ),
    //   scope.row.enabled !== 1 ? (
    //     <el-tag type="info">
    //       {useDictionary("Enabled", scope.row.enabled)}
    //     </el-tag>
    //   ) : (
    //     <el-tag type="success">
    //       {useDictionary("Enabled", scope.row.enabled)}
    //     </el-tag>
    //   ),
  },
  {
    prop: "usingDepartmentName",
    label: "使用部门",
    isShow: true,
    align: "left",
    sortable: "sortable",
    minWidth: "120",
  },

  {
    prop: "usingPersonName",
    label: "使用人员",
    isShow: true,
    sortable: "sortable",
    minWidth: "120",
  },
  {
    prop: "locationName",
    label: "器具位置",
    isShow: true,
    align: "left",
    sortable: "sortable",
    minWidth: "120",
  },
  {
    prop: "assetStatus",
    label: "器具状态",
    sortable: "sortable",
    isShow: true,
    minWidth: "120",
    render: (scope: any) =>
      useDictionary("mtAssetStatus", scope.row.assetStatus),
  },
  {
    prop: "checkPlace",
    label: "检定地点",
    isShow: true,
    align: "left",
    sortable: "sortable",
    minWidth: "120",
  },
  {
    prop: "checkPerson",
    label: "检定人员",
    sortable: "sortable",
    minWidth: "120",
    isShow: true,
  },
]);

// 是否显示搜索框
const showSearch = ref(true);

/** 列表项自定义方法   end **/

// 请求参数
const requestApi = "/eam/mtAssetInfo/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = reactive({
  sort: {
    column: "",
    orderBy: "",
  },
});

// 初始化搜索参数数据
const searchParamInit = {
  assetName: "",
  assetCode: "",
  assetTypeId: "",
  locationId: "",
  usingDepartmentId: "",
  assetStatus: "",
  manageDepartmentId: "",
  checkPerson: "",
  nextCheckDateSearch: [],
  nextCheckDateStart: "",
  nextCheckDateEnd: "",
  productId: "",
};

const deleteParam = {
  api: "/system/databoradinfo/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

// 排序
// 监听表格排序方法
function onTableSortChanged(column: any) {
  const { prop, order } = column;
  console.log(prop, order);

  initParam.sort = {
    column: prop,
    orderBy: filterOrder(order),
  };
}
// 监听页面 initParam 改化，重新获取表格数据
watch(() => initParam, getTableList, { deep: true });

/** 选择组织机构并赋值id  start **/
function getSelectIds(ids: [] | string, item: string) {
  if (item == "使用部门") {
    searchParam.value.usingDepartmentId = ids;
  } else if (item == "管理部门") {
    searchParam.value.manageDepartmentId = ids;
  }
}
const dataObject = (item: string) => {
  return {
    name: item == "使用部门" ? "使用部门" : "管理部门",
    defaultProps: {
      children: "nodes",
      label: "organizationName",
      value: "id",
    },
    api: "/system/sysOrganization/getUsableTree",
  };
};

// 获取位置信息下拉树
const locationInfoTree = ref([]);
const getLocationInfoTree = async () => {
  const { data } = await request({
    url: "/eam/locationInfo/getTree",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  locationInfoTree.value = data;
};

// 获取位置信息下拉树
const productList = ref([]);
const getProductList = async () => {
  const { data } = await request({
    url: "/mdm/mdmproductinfo/getList",
    method: "POST",
    data: {
      enabled: 1,
    },
  });
  productList.value = data;
  console.log(productList.value);
};
// // 获取制造商列表
// const makerList: any = ref([]);
// const getMakerList = async () => {
//   request({
//     url: `/eam/eammaker/getList`,
//     method: "post",
//     data: {},
//   })
//     .then((res) => {
//       makerList.value = res.data;
//     })
//     .catch((res) => {
//       console.log(res);
//     });
// };

// 处理时间
function getcreateTime(data: any) {
  if (data) {
    searchParam.value.nextCheckDateStart = data[0];
    searchParam.value.nextCheckDateEnd = data[1];
  } else {
    searchParam.value.nextCheckDateStart = "";
    searchParam.value.nextCheckDateEnd = "";
  }
}
onMounted(() => {
  getLocationInfoTree();
  // getMakerList();
  getTableList();
  getProductList();
});

// const addDialog = reactive<DialogOption>({
//   visible: false,
//   readvisible: false,
//   title: "",
//   data: {},
// });

// // 查询详情
// async function getInfo(id: string) {
//   request({
//     url: `/system/databoradinfo/get/${id}`,
//     method: "get",
//   })
//     .then((data) => {
//       addDialog.data = data.data;
//       addDialog.visible = true;
//     })
//     .catch((res) => {
//       console.log(res);
//     });
// }

// /** 打开数据看板表单弹窗 */
// function openDialog(roleObj?: Object) {
//   if (roleObj) {
//     addDialog.title = "修改数据看板";
//     getInfo(roleObj.id);
//   } else {
//     addDialog.title = "新增数据看板";
//     addDialog.visible = true;
//   }
//   addDialog.readvisible = false;
// }

// /** 打开数据看板表单弹窗 详情 */
// function openDialogdetail(roleObj?: any) {
//   addDialog.title = "数据看板详情";
//   getInfo(roleObj.id);
//   addDialog.readvisible = true;
// }

// function changeVisible(value: boolean) {
//   addDialog.visible = value;
//   if (!value) {
//     addDialog.data = {};
//   }
// }

// 目录树
const catalogList: any = ref([]);

// 获取内容树数据
const getCAtalogList = async () => {
  // 获取内容树
  await request({
    url: "eam/mtAssetType/getAvailableTree",
    method: "POST",
    data: {},
  }).then((res) => {
    catalogList.value = res.data;
  });
};
onMounted(() => {
  getCAtalogList();
});
</script>
<style lang="scss" scoped>
@media only screen and (max-width: 768px) {
  .el-col-xs-24 {
    padding-right: 10px !important;
  }
}
</style>
